package org.fang.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.fang.admin.common.convention.exception.ClientException;
import org.fang.admin.common.enums.UserErrorCodeEnum;
import org.fang.admin.dao.entity.UserDO;
import org.fang.admin.dao.mapper.UserMapper;
import org.fang.admin.dto.req.UserLoginReqDTO;
import org.fang.admin.dto.req.UserRegisterReqDTO;
import org.fang.admin.dto.req.UserUpdateReqDTO;
import org.fang.admin.dto.resp.UserLoginRespDTO;
import org.fang.admin.dto.resp.UserRespDTO;
import org.fang.admin.service.GroupService;
import org.fang.admin.service.UserService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static org.fang.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static org.fang.admin.common.constant.RedisCacheConstant.USER_LOGIN_KEY;
import static org.fang.admin.common.enums.UserErrorCodeEnum.*;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;
    private final RedissonClient redissonClient;
    private final StringRedisTemplate stringRedisTemplate;
    private final GroupService groupService;

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    public UserRespDTO getUserByUsername(String username) {
        // 1.使用mp根据用户名查询用户
        LambdaQueryWrapper<UserDO> eq = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getUsername, username);
        UserDO userDO = baseMapper.selectOne(eq);
        if (userDO == null) {
            throw new ClientException(UserErrorCodeEnum.USER_NULL);
        }
        // 2.封装
        UserRespDTO userRespDTO = new UserRespDTO();
        BeanUtils.copyProperties(userDO, userRespDTO);
        return userRespDTO  ;
    }

    /**
     * 查询用户名是否存在
     */
    public Boolean hasUsername(String username) {
        // 用户名存在的话就返回false，提醒用户该用户名已存在，不允许注册了
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    /**
     * 注册用户
     * @param requestParam
     */
    public void register(UserRegisterReqDTO requestParam) {
        if (!hasUsername(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }

        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());
        try {
            // 获取到锁
            if (lock.tryLock()) {
                // mybatis-plus向数据库中插入要注册的信息
                try {
                    int inserted = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
                    if (inserted < 1) {
                        throw new ClientException(USER_SAVE_ERROR);
                    }
                }catch (DuplicateKeyException e){
                    throw new ClientException(USER_EXIST);
                }
                // 向布隆过滤器中加入要注册的信息，下次查询的时候就从这里查
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
                groupService.saveGroup(requestParam.getUsername(),"默认分组");
                return;
            }
            // 没有获取到锁
            throw new ClientException(USER_NAME_EXIST);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 根据用户名修改用户信息
     * @param requestParam
     */
    public void update(UserUpdateReqDTO requestParam) {
        // todo 验证当前用户名是否为登录用户名
        LambdaUpdateWrapper<UserDO> eq = Wrappers.lambdaUpdate(UserDO.class).eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class), eq);
    }

    /**
     * 用户登录
     * @param requestParam
     * @return
     */
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {
        // 1.检验传过来的用户信息是否合法
        LambdaQueryWrapper<UserDO> eq = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);
        UserDO user = baseMapper.selectOne(eq);
        // 2.如果为空，抛异常
        if (user == null) {
            throw new ClientException("用户不存在");
        }
        // 3.判断当前登录用户是否重复登录
        Map<Object, Object> hasLoginMap = stringRedisTemplate.opsForHash().entries(USER_LOGIN_KEY + requestParam.getUsername());
        if (CollUtil.isNotEmpty(hasLoginMap)) {
            stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
            String token = hasLoginMap.keySet().stream()
                    .findFirst()
                    .map(Object::toString)
                    .orElseThrow(() -> new ClientException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }
        /**
         * Hash
         * Key：login_用户名
         * Value：
         *  Key：token标识
         *  Val：JSON 字符串（用户信息）
         */
        // 4.如果不是重复登陆，则先将用户信息存入redis
        String uuid = UUID.randomUUID().toString();
        stringRedisTemplate.opsForHash().put(USER_LOGIN_KEY + requestParam.getUsername(), uuid, JSON.toJSONString(user));
        // 设置过期时间
        stringRedisTemplate.expire(USER_LOGIN_KEY + requestParam.getUsername(), 30L, TimeUnit.MINUTES);
        return new UserLoginRespDTO(uuid);
    }

    /**
     * 检查当前用户是否为登录用户
     * @param token
     * @return
     */
    public Boolean checkLogin(String username, String token) {
        // 检查redis中是否有传过来的token，有的话那就为登录用户
        return stringRedisTemplate.opsForHash().get(USER_LOGIN_KEY + username, token) != null;
    }

    /**
     * 用户退出登录
     * @param username
     * @param token
     * @return
     */
    public void logout(String username, String token) {
        // 1.验证当前用户是否为登录用户
        if (checkLogin(username, token)) {
            // 2.如果是，则退出,删除redis中的登录用户信息
            stringRedisTemplate.delete(USER_LOGIN_KEY + username);
            return;
        }
        // 3.如果不是，则报异常
        throw new ClientException("用户未登录");
    }
}
